import { ItemData, PlayerData } from "./Datas/Data";
import { Constant } from "./Framework/Const/Constant";
import { PoolManager } from "./Framework/Managers/PoolManager";
import NodeUtil from "./Framework/Utils/NodeUtil";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Bullet extends cc.Component {

    rigidbody: cc.RigidBody = null;
    target: cc.Node = null;
    weapon = null;
    playerData: PlayerData = null;

    onLoad() {
        this.rigidbody = this.node.getComponent(cc.RigidBody);
    }

    Init(target: cc.Node, weapon: ItemData, playerData: PlayerData) {
        this.target = target;
        this.weapon = weapon;
        this.playerData = playerData;
        let speed = cc.v2(this.node.right.clone().multiplyScalar(10000));
        // let speed = cc.v2(this.node.right.clone().multiplyScalar(2000));
        this.rigidbody.applyForceToCenter(speed, true);
    }

    //子弹抛壳
    InitBlank(target: cc.Node, impulse: cc.Vec2, point: cc.Vec2) {
        this.target = target;
        this.rigidbody.applyLinearImpulse(impulse, point, true);
    }

    onBeginContact(contact: cc.PhysicsContact, self, other) {
        if (other.node.group == Constant.Group.Obstacle) {
            const worldManifold = contact.getWorldManifold();

            PoolManager.GetNode("Prefabs/Explosion", cc.director.getScene()).then(node => {
                NodeUtil.SetWorldPosition(node, worldManifold.points[0]);
                node.angle = cc.misc.radiansToDegrees(cc.Vec2.RIGHT.signAngle(worldManifold.normal.negate()));
            });

            PoolManager.PutNode(this.node);
        }
    }

    update(dt) {
        if (this.target) {
            if (cc.Vec2.distance(NodeUtil.GetWorldPosition(this.node), NodeUtil.GetWorldPosition(this.target)) > 3500) {
                PoolManager.PutNode(this.node);
            }
        } else {
            PoolManager.PutNode(this.node);
        }
    }
}